package nimbus.mvc
{
	import flash.events.EventDispatcher;
	import flash.utils.IDataInput;
	import flash.utils.IDataOutput;
	import flash.utils.IExternalizable;
	import flash.utils.describeType;

	public class ValueObject extends EventDispatcher implements IExternalizable
	{
		
		public function writeExternal(output:IDataOutput):void
		{
			output.writeObject(getVO());
		}
		
		public function readExternal(input:IDataInput):void
		{
			var obj:Object = input.readObject();
			setVO(obj);
		}
		
		/**
		 * Sets the "VO" values of this object
		 */
		public function setVO(obj:Object):void
		{
			for (var i:String in obj)
				try { this[i] = obj[i]; } catch (e:Error) {}
		}
		
		/**
		 * Returns the "VO" representation of this object (an anonymous object)
		 */
		public function getVO():Object
		{
			var obj:Object = {};
			
			var desc:XML = describeType(this);
			var props:XMLList = (desc.accessor + desc.variable).(/String|int|uint|Number|Boolean|Date/.test(@type.toString())).@name;
			
			for (var i:uint = 0; i < props.length(); i++)
				obj[props[i]] = this[props[i]];
			
			return obj;
		}
	}
}
